const path = require('path')
const Koa = require('koa')
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser")
const koaStatic = require("koa-static")
const structureBody = require('./src/utils/structureBody')

// 连接数据库
require('./src/database/connect')

const app = new Koa()

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method.toLowerCase() === 'options') {
    ctx.body = 200
  } else {
    await next()
  }
})

app.use(koaStatic(path.join(path.dirname(__dirname), "public")))
app.use(bodyParser())
app.use(structureBody())

const router = new Router()

const user = require('./src/routes/user')
router.use('/api/user', user)

app.use(router.routes())

const port = '2020'
app.listen(port)
console.log(`服务启动成功！监听端口：${port}`)